﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
#if(NET35)
using LightFx.Linq.Expressions;
#endif
using System.Linq.Expressions;


namespace Orm.LinqParse
{
    /// <summary>
    /// 处理各种where和selelct的表达式
    /// 作者:蒋大为
    /// </summary>
    internal class SelectTranslator : ExpressionVisitor
    {
        private List<string> filedNames;

        public List<string> GetName(Expression expression)
        {
            this.Visit(expression);
            return filedNames;
        }

#if(NET35)
        protected override Expression VisitMemberAccess(MemberExpression m)
#endif
#if(NET4)
        protected override Expression VisitMember(MemberExpression m)
#endif
        {
            if (m.Expression != null && m.Expression.NodeType == ExpressionType.Parameter)
            {
                if (filedNames == null) 
                    filedNames = new List<string>();
                filedNames.Add(m.Member.Name);
                return m;
            }
            throw new NotSupportedException(string.Format("The member '{0}' is not supported", m.Member.Name));
        }

        protected override Expression VisitParameter(ParameterExpression p)
        {
            //如果表达式像 linq.Select(q=>q); 这样则选择所有字段。 
            //filedNames = new List<string>() { "*" };
            filedNames = p.Type.GetProperties().Select(i =>(i.Name)).ToList();
            return p;
        }
    }
}
